package com.qianfeng.es.service.impl;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import com.qianfeng.es.service.DcoService;
import com.qianfeng.es.utils.ConnectionUtil;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.*;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;

import javax.lang.model.element.VariableElement;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jackiechan on 2022/2/16/21:46
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
public class DcoServiceImpl implements DcoService {

    RestHighLevelClient client = ConnectionUtil.getClient();

    @Override
    public void addDoc(String indexName, String json) throws Exception {

        IndexRequest request = new IndexRequest(indexName);
        request.source(json, XContentType.JSON);//设置数据源,也就是要插入的数据以及格式
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.err.println(response);
    }

    @Override
    public void addDoc(String indexName, String id, String json) throws Exception {
        IndexRequest request = new IndexRequest(indexName);
        request.source(json, XContentType.JSON).id(id);//设置数据源,也就是要插入的数据以及格式以及指定id
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        System.err.println(response);
    }

    @Override
    public void getDataById(String indexName, String id) throws Exception {
        GetRequest request = new GetRequest(indexName, id);
        GetResponse getResponse = client.get(request, RequestOptions.DEFAULT);
        System.err.println(getResponse);
    }

    @Override
    public void updateDoc(String indexName, String id, String json) throws Exception {
        UpdateRequest request = new UpdateRequest(indexName, id).doc(json, XContentType.JSON);
        UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
        System.err.println(response);
    }

    @Override
    public void termQuery(String index, String field, String value) throws Exception {
//        SearchRequest searchRequest = new SearchRequest(index);
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//设置查询条件的builder,建造者,需要调用里面的一些方法设置内容
//       // sourceBuilder.query(new TermQueryBuilder(field,value));
//        sourceBuilder.query(QueryBuilders.termQuery(field, value));
//        searchRequest.source(sourceBuilder);//设置搜索的builder
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchResponse response = baseQuery(index, QueryBuilders.termQuery(field, value));
        System.err.println(response);
    }

    @Override
    public void termsQuery(String index, String field, String... value) throws Exception {
//        SearchRequest searchRequest = new SearchRequest(index);
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        sourceBuilder.query(QueryBuilders.termsQuery(field, value));
//        searchRequest.source(sourceBuilder);//设置搜索的builder
//        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchResponse response = baseQuery(index, QueryBuilders.termsQuery(field, value));
        System.err.println(response);
    }

    @Override
    public void matchAllQuery(String index) throws Exception {
        SearchResponse response = baseQuery(index, QueryBuilders.matchAllQuery());
        System.err.println(response);
    }

    @Override
    public void matchQuery(String index, String field, String value) throws Exception {
        SearchResponse response = baseQuery(index, QueryBuilders.matchQuery(field,value));
        System.err.println(response);
    }

    @Override
    public void boolMatchQuery(String index, String field, String value, Operator operator) throws Exception {
        SearchResponse response = baseQuery(index, QueryBuilders.matchQuery(field,value).operator(operator));
        System.err.println(response);
    }

    @Override
    public void multiMatch(String index, String value, String... field) throws Exception {
        SearchResponse response = baseQuery(index, QueryBuilders.multiMatchQuery(value,field));
        System.err.println(response);

    }

    @Override
    public void idsQuery(String index, String... value) throws Exception {
        SearchResponse response = baseQuery(index, QueryBuilders.idsQuery().addIds(value));
        System.err.println(response);
    }

    @Override
    public void prefixQuery(String index, String field, String value) throws Exception {
        SearchResponse response = baseQuery(index, QueryBuilders.prefixQuery(field,value));
        System.err.println(response);
    }

    @Override
    public void deleteByQuery(String index,QueryBuilder query) throws Exception {
        DeleteByQueryRequest request = new DeleteByQueryRequest(index);
        request.setQuery(query);
        BulkByScrollResponse response = client.deleteByQuery(request, RequestOptions.DEFAULT);
        System.err.println(response);
    }

    @Override
    public SearchResponse scrcollQuery(String index, QueryBuilder queryBuilder, String time) throws Exception {
        SearchRequest searchRequest = new SearchRequest(index);
        searchRequest.scroll(time);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.size(1);
        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);//设置搜索的builder
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        return response;
    }

    @Override
    public SearchResponse scrollQuery( String scrollId, String time) throws Exception {
        SearchScrollRequest searchScrollRequest = new SearchScrollRequest(scrollId);
        searchScrollRequest.scroll(time);
        SearchResponse response = client.scroll(searchScrollRequest, RequestOptions.DEFAULT);
        return response;
    }

    @Override
    public void clearScroll(String scrollId) throws Exception {
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        clearScrollRequest.addScrollId(scrollId);
        ClearScrollResponse response = client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
        System.err.println(response);
    }

    @Override
    public void highLightQuery(String index, String field, String value) throws Exception {
        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        HighlightBuilder highlightBuilder = new HighlightBuilder();//设置高亮
        highlightBuilder.field(field);//设置返回结果中哪个列会将查询的条件高亮显示
        highlightBuilder.fragmentSize(0);//对应高亮数据的列的结果全部返回
        highlightBuilder.preTags("<span color='red'>");//设置高亮的前置标签
        highlightBuilder.postTags("</span");//设置高亮的后置标签
        sourceBuilder.highlighter(highlightBuilder);//设置高亮的查询
        sourceBuilder.query(QueryBuilders.matchQuery(field, "盒马"));

        searchRequest.source(sourceBuilder);//设置请求的查询条件等参数
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = response.getHits();//获取命中的数据
        SearchHit[] hits1 = hits.getHits();//获取到真正的数据
        for (SearchHit searchHit : hits1) {
            //遍历获取每一条数据
            Map<String, Object> sourceAsMap = searchHit.getSourceAsMap();//以map的方式保存结果
         //   String sourceAsString = searchHit.getSourceAsString();//这是以json格式的字符串做结果
            HighlightField highlightField = searchHit.getHighlightFields().get(field);//获取指定名字的高亮的数据
            if (highlightField != null) {//获取返回结果的高亮部分,注意可能没有,必须要判空
                Text[] fragments = highlightField.getFragments();
                if (fragments != null) {
                    String gaoliangshuju = fragments[0].toString();
                    sourceAsMap.put(field, gaoliangshuju);//用高亮数据替换之前的数据
                }
            }
            System.err.println(sourceAsMap);
        }
    }


    public SearchResponse baseQuery(String index, QueryBuilder queryBuilder) throws Exception{
        SearchRequest searchRequest = new SearchRequest(index);
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(queryBuilder);
        searchRequest.source(sourceBuilder);//设置搜索的builder
        SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
        return response;
    }
}
